<template>
  <a-drawer
    :title="title"
    :width="720"
    :visible.sync="visible"
    :body-style="{ paddingBottom: '80px' }"
    :footer-style="{ textAlign: 'right' }"
    @close="onClose"
  >
    <a-form ref="myForm" layout="horizontal" :model="formData" size="small">
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="Name" name="name">
            <a-input size="small" v-model="formData.name" placeholder="输入名称" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="请求方式" name="httpMethod">
            <a-select size="small" v-model="formData.httpMethod" :showSearch="true" placeholder="选择请求方式">
              <a-select-option v-for="method in httpMethodsRadios" :key="method" :value="method">
                {{ method }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="enable">
            <a-radio-group size="small" v-model:value="formData.enable">
              <a-radio-button value="1">启用</a-radio-button>
              <a-radio-button value="0">禁用</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="16">
          <a-form-item label="响应状态" name="httpStatus">
            <a-select size="small" v-model:value="formData.httpStatus" :showSearch="true" placeholder="选择响应码">
              <a-select-option v-for="status in httpStatusOptions" :key="status.value">
                {{ '[' + status.value + '] ' + status.reasonPhrase }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="响应头" name="header">
            <a-row :gutter="16" v-for="(header, idx) in formData.customHeader" :key="idx">
              <a-col :span="9">
                <a-select size="small" v-model="header.name" :showSearch="true" allowClear placeholder="选择响应头">
                  <a-select-option
                    size="small"
                    v-for="(httpHeader, index) in filterHttpHeaders"
                    :key="httpHeader"
                    :value="httpHeader"
                  >
                    {{ httpHeader }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="9">
                <a-input size="small" v-model="formData.customHeader[idx].value" allowClear />
              </a-col>
              <a-col :span="6">
                <a-space style="width: 100%">
                  <a-button size="small" type="primary" @click="moreHeader()">
                    <a-icon type="plus" />
                  </a-button>
                  <a-button size="small" v-if="showHeadersMinisButton" type="danger" @click="lessHeader(idx)">
                    <a-icon type="minus" />
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="消息体" name="content">
            <a-textarea size="small" v-model:value="formData.content" :rows="4" allow-clear></a-textarea>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="备注" name="remark">
            <a-textarea size="small" v-model:value="formData.remark" :rows="4" placeholder="备注" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-space>
      <a-button size="small" @click="onClose">取消</a-button>
      <a-button size="small" type="primary" @click="onSubmit">提交</a-button>
      <a-button
        size="small"
        @click="
          () => {
            this.formData = { ...this.formData, ...this.initForm() }
          }
        "
        >随机</a-button
      >
    </a-space>
  </a-drawer>
</template>
<script>
import { failmsg } from '@/api/api'
import { create, getHttpHeaders, getHttpMethods, getHttpStatus, update } from '@/api/mock-url-response'
import Mock from 'mockjs2'
import vueJsonEditor from 'vue-json-editor'

export default {
  name: 'CreateResponse',
  components: {
    vueJsonEditor,
  },
  props: {
    urlId: {
      type: String,
      default: null,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    form: {
      type: Object,
      default: {},
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    getHttpMethods().then((res) => (this.httpMethodsRadios = res))
    getHttpHeaders().then((res) => (this.httpHeaders = res))
    getHttpStatus().then((res) => (this.httpStatusOptions = res))
  },
  data() {
    return {
      title: '',
      httpMethodsRadios: [],
      httpStatusOptions: [],
      httpHeaders: [],
      formData: {},
      jsonEditorModel: 'text',
    }
  },
  computed: {
    showHeadersMinisButton() {
      return this.formData.customHeader.length > 1
    },
    filterHttpHeaders() {
      return this.httpHeaders.filter((i) => !_.map(this.formData.customHeader, (n) => n.name).includes(i))
    },
  },
  methods: {
    onClose() {
      this.formData = this.initForm()
      this.$emit('handle-cancel')
    },
    onContentChg(value) {
      debugger
      this.onContentSave(value)
    },
    onContentSave(value) {
      if (value instanceof Object) {
        this.formData.content = JSON.stringify(value)
      } else {
        this.formData.content = value
      }
    },
    onSubmit() {
      const param = this.formData
      if (param.id) {
        update(param)
          .then(() => {
            this.$emit('handle-ok')
          })
          .catch((err) => failmsg(err))
      } else {
        create(param)
          .then(() => {
            this.$emit('handle-ok')
          })
          .catch((err) => failmsg(err))
      }
    },
    moreHeader() {
      this.formData.customHeader.push({ name: '', value: '' })
    },
    lessHeader(index) {
      this.formData.customHeader.splice(index, 1)
    },
    initForm() {
      const randomHttpStatus = Mock.mock({
        'array|1': this.httpStatusOptions.map((item) => item.value),
      })
      const randomHttpMethod = Mock.mock({
        'array|1': this.httpMethodsRadios,
      })
      return {
        urlId: this.urlId,
        name: Mock.mock('@title(3,8)'),
        customHeader: [
          {
            name: 'Content-Type',
            value: 'application/json',
          },
        ],
        httpStatus: randomHttpStatus.array,
        httpMethod: randomHttpMethod.array,
        enable: '0',
        content: Mock.mock('@sentence()'),
        remark: Mock.mock('@sentence()'),
      }
    },
  },
  watch: {
    form: {
      handler(newValue) {
        console.log(this.isEdit)
        if (this.isEdit) {
          this.formData = { ...newValue }
          this.title = '编辑响应'
        } else {
          this.formData = { ...this.initForm() }
          this.title = '新建响应'
        }
      },
      immediate: true,
    },
  },
}
</script>
